#import <stdlib.h>
#import <Ice/Ice.h>
#import "eventSupplier.h"
#import "event.h"

@implementation EventSupplier

-(id) initWithCommunicator:(id<ICECommunicator>)communicator andHost:(NSString*)host
{
	if (![super init])
		return nil;
		
	comm = communicator;
	
	[self createSupplier:host];
	
	return self;
}

-(void) dealloc
{
	[supplier release];
	
	[super dealloc];
}

-(void) push:(CollaborationMutableEvent*)evt current:(ICECurrent *)current
{
	[supplier push:evt];
}

-(void) createSupplier:(NSString*)host
{
	id<ICEObjectPrx> topic = nil; /**< Proxy hacia el topico de la suscripcion */
	
	NSString* aux = [NSString stringWithFormat:@"DemoIceStorm/TopicManager:tcp -h %@ -p 10000", host];
	id<ICEObjectPrx> manager = [comm stringToProxy:aux];
    if(!manager)
    {
		@throw [NSException exceptionWithName:@"InvalidProxyException" reason:@"Invalid supplier proxy" userInfo:nil];
    }

    @try
    {
        //topic = manager->retrieve("events");
		id<ICEInputStream> is = nil;
		id<ICEOutputStream> os = [manager createOutputStream__];
		[os writeString:@"events"];
		
		[manager invoke__:@"retrieve" mode:ICEIdempotent os:os is:&is context:[manager ice_getContext]];
		
		topic = [ICEObjectPrx ice_readWithStream:is];
    }
    @catch(ICEException* e1)
    {
        @try
        {
            //topic = manager->create("events");
			id<ICEInputStream> is = nil;
			id<ICEOutputStream> os = [manager createOutputStream__];
			[os writeString:@"events"];
			
			[manager invoke__:@"create" mode:ICENormal os:os is:&is context:[manager ice_getContext]];
			
			topic = [ICEObjectPrx ice_readWithStream:is];
        }
        @catch(ICEException* e2)
        {
			@throw [NSException exceptionWithName:@"ConnectionFailureException" reason:@"Temporary failure. try again." userInfo:nil];
        }
    }

    //Ice::ObjectPrx publisher = topic->getPublisher();
    //supplier = collaboration::EventSupplierPrx::uncheckedCast(publisher);

	id<ICEInputStream> is = nil;
	id<ICEOutputStream> os = [topic createOutputStream__];
	
	[topic invoke__:@"getPublisher" mode:ICEIdempotent os:os is:&is context:[topic ice_getContext]];
	
	id<ICEObjectPrx> publisher = [ICEObjectPrx ice_readWithStream:is];
	
	supplier = [[CollaborationEventSupplierPrx uncheckedCast:publisher] retain];
	
	supplier = [supplier ice_oneway];
	
	[topic release];
}

@end
